import React, { useEffect, useRef, useState } from 'react';
import axios from 'axios'
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import CameraAltIcon from '@mui/icons-material/CameraAlt';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import md5 from 'md5';
import { useNavigate } from 'react-router-dom';

export default function AnalysisPage() {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const [photo, setPhoto] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(0); // 可选，模拟进度
  const navigate = useNavigate();

  useEffect(() => {
    navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
      const video = videoRef.current;
      if (video) {
        video.srcObject = stream;
      }
    });
    return () => {
      const video = videoRef.current;
      if (video) {
        const stream = video.srcObject as MediaStream;
        if (stream) {
          stream.getTracks().forEach(track => track.stop());
        }
      }
    };
  }, []);

  function base64ToBlob(base64: string, mime = 'image/jpeg') {
    const byteString = atob(base64);
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], { type: mime });
  }
  const [pifuresult, setpifu] = useState({})
  const takePhoto = async () => {
    setLoading(true);
    setProgress(0);

    // 模拟进度（可选）
    const timer = setInterval(() => {
      setProgress(prev => {
        if (prev >= 90) {
          clearInterval(timer);
          return prev;
        }
        return prev + 10;
      });
    }, 300);

    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (video && canvas) {
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataUrl = canvas.toDataURL('image/jpeg');
      setPhoto(dataUrl);

      // 提取 base64 数据
      const base64 = dataUrl.replace(/^data:image\/jpeg;base64,/, '');
      const blob = base64ToBlob(base64, 'image/jpeg');
      // 检查图片大小
      if (blob.size > 2 * 1024 * 1024) {
        alert('图片过大，请调整分辨率或压缩后再试');
        return;
      }

      const formData = new FormData();
      formData.append('image', blob, 'photo.jpg');

      // 可选：打印formData内容
      for (let [key, value] of formData.entries()) {
        console.log('formData:', key, value);
      }

      try {
        const timestamp = Date.now();
        const secret = 'SKINSDFSLDFKLJLKDSFSLKFJSFK90';
        const sign = md5(timestamp + secret);

        formData.append('age', '19');
        const response = await axios.post(
          'https://api.skinrun.cn/face',
          formData,
          {
            headers: {
              'token': '606824C00098BF7D6A3862C0342752C0',
              'version': '2.0',
              'time': timestamp,
              'sign': sign
            }
          }
        );
        console.log('AI接口返回:', response.data);
        if (response.data.code === 200) {
          // setpifu(response.data.data);
          // 本地存储每一次的请求结果（最多3条）
          let history = JSON.parse(localStorage.getItem('pifuresult_history') || '[]');
          const newResult = { ...response.data.data, time: Date.now() };
          history.unshift(newResult);
          if (history.length > 3) history = history.slice(0, 3);
          localStorage.setItem('pifuresult_history', JSON.stringify(history));
          localStorage.setItem('pifuresult', JSON.stringify(response.data.data)); // 保持原有单条
          // 跳转页面
          navigate('/app/result', { state: { pifuresult: response.data.data } });
        } else {
          console.error('API错误:', response.data.message);
        }
        setProgress(100);
      } catch (err: any) {
        if (err && err.response) {
          console.log('上传失败', err.response.data);
        } else {
          console.log('上传失败', err);
        }
      } finally {
        setLoading(false);
      }
    }
  };

  return (
    <Box sx={{
      background: '#f7f7fa',
      minHeight: '100vh',
      width: '100vw',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      fontFamily: 'PingFang SC, Helvetica Neue, Arial, sans-serif'
    }}>
      {/* 顶部栏 */}
      <Box sx={{
        width: '100vw',
        margin: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 56,
        px: 2,
        background: '#fff',
        borderBottom: '1px solid #eee',
        position: 'sticky',
        top: 0,
        zIndex: 10
      }}>
        <IconButton onClick={() => navigate('/app/shou')}>
          <ArrowBackIosNewIcon />
        </IconButton>
        <Typography sx={{ fontWeight: 600, fontSize: 20, letterSpacing: 1 }}>检查你的脸</Typography>
        <IconButton>
          <HelpOutlineIcon />
        </IconButton>
      </Box>

      {/* 摄像头画面区域 */}
      <Box sx={{
        width: '100vw',
        height: '60vh',
        margin: '32px 0 0 0',
        background: '#fff',
        borderRadius: 0,
        boxShadow: 'none',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center'
      }}>
        <Box sx={{
          width: '100vw',
          height: '100%',
          background: '#eaeaea',
          position: 'relative',
        }}>
          <video ref={videoRef} autoPlay playsInline style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            display: photo ? 'none' : 'block'
          }} />
          {photo && <img src={photo} alt="拍照" style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            position: 'absolute',
            top: 0,
            left: 0
          }} />}
        </Box>
      </Box>
      <canvas ref={canvasRef} style={{ display: 'none' }} />

      {/* 拍照按钮和提示 */}
      <Box sx={{ textAlign: 'center', mt: 5 }}>
        <IconButton
          onClick={takePhoto}
          sx={{
            background: 'linear-gradient(135deg, #7356f1 60%, #b48af7 100%)',
            color: '#fff',
            width: 72,
            height: 72,
            borderRadius: '50%',
            fontSize: 36,
            mb: 2,
            boxShadow: '0 4px 16px 0 rgba(115,86,241,0.13)',
            transition: 'transform 0.18s, box-shadow 0.18s',
            '&:hover': {
              background: 'linear-gradient(135deg, #5a3fd1 60%, #a07be0 100%)',
              transform: 'scale(1.07)'
            }
          }}
        >
          <CameraAltIcon fontSize="inherit" />
        </IconButton>
        <Typography sx={{ color: '#999', fontSize: 15, mt: 2 }}>
          确保没有任何东西挡住您的脸
        </Typography>
      </Box>

      {/* 进度环遮罩层（保持原样） */}
      {loading && (
        <Box
          sx={{
            position: 'fixed',
            left: 0,
            top: 0,
            width: '100vw',
            height: '100vh',
            bgcolor: 'rgba(0,0,0,0.4)',
            zIndex: 9999,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          {/* 进度环 */}
          <Box sx={{ mb: 2 }}>
            <svg width="100" height="100">
              <circle
                cx="50"
                cy="50"
                r="40"
                stroke="#eee"
                strokeWidth="8"
                fill="none"
              />
              <circle
                cx="50"
                cy="50"
                r="40"
                stroke="#7356f1"
                strokeWidth="8"
                fill="none"
                strokeDasharray={2 * Math.PI * 40}
                strokeDashoffset={2 * Math.PI * 40 * (1 - progress / 100)}
                strokeLinecap="round"
                style={{ transition: 'stroke-dashoffset 0.3s' }}
              />
              <text
                x="50"
                y="58"
                textAnchor="middle"
                fontSize="24"
                fill="#fff"
              >
                {progress}%
              </text>
            </svg>
          </Box>
          <Typography sx={{ color: '#fff', fontSize: 18, mb: 1 }}>
            分析正在进行中，请勿关闭
          </Typography>
        </Box>
      )}
    </Box>
  );
}

